package com.shiro.cusrealm;


import com.shiro.dao.UserDao;
import com.shiro.model.User;
import com.shiro.util.DbUtil;
import com.shiro.util.ShiroUtil;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.Subject;

import javax.annotation.Resource;
import java.sql.Connection;

/**
 * @author gaoxu
 * @date 2019-05-13 11:14
 * @description ... 类
 */
public class CusRealm extends AuthorizingRealm {

    @Resource
    private UserDao userDao;

    /**
     * 授权：在身份认证通过后，shiro自动调用这个方法给认证主体设置角色和权限
     *
     * @param principalCollection
     * @return
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();
        Connection conn = null;
        String userName = (String) principalCollection.getPrimaryPrincipal();
        try {
            conn = DbUtil.getConn();
            authorizationInfo.setRoles(userDao.getRolesByUserName(conn, userName));
            authorizationInfo.setStringPermissions(userDao.getPermissionsByUserName(conn, userName));
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                DbUtil.closeConn(conn);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return authorizationInfo;
    }

    /**
     * 认证：在subject.login(token)时，调用此方法，shiro会对比返回的authenticationInfo与传入的token
     *
     * @param token
     * @return
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        AuthenticationInfo authenticationInfo = null;
        Connection conn = null;
        //1.token身份
        String userName = (String) token.getPrincipal();
        try {
            conn = DbUtil.getConn();
            //2.认证主体
            User user = userDao.getUserByUserName(conn, userName);
            if (user != null) {
                //3.认证信息
                authenticationInfo = new SimpleAuthenticationInfo(user.getUserName(), user.getPassword(), "这个内容随便写");
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                DbUtil.closeConn(conn);
            } catch (Exception e) {
                e.printStackTrace();
            }

        }
        return authenticationInfo;
    }


    public static void main(String[] args) {

        Subject subject = ShiroUtil.login("classpath:cus_realm.ini", "java1234", "1234");

        subject.logout();
    }
}
